'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-client';
import { motion } from 'framer-motion';
import { 
  ArrowLeft, 
  TrendingUp, 
  TrendingDown, 
  Target, 
  Clock, 
  Award,
  CheckCircle,
  Calendar,
  BarChart3
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';

interface ReportData {
  period: string;
  days: number;
  summary: {
    totalQuestions: number;
    totalCorrect: number;
    accuracy: number;
    totalTime: number;
    avgTimePerDay: number;
    practiceDays: number;
  };
  strongTopics: any[];
  weakTopics: any[];
  trend: any[];
  progressTrend: string;
  suggestions: string[];
}

export default function ReportsPage() {
  const router = useRouter();
  const { user, loading: authLoading } = useAuth();
  const [reportType, setReportType] = useState<'weekly' | 'monthly'>('weekly');
  const [report, setReport] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!authLoading) {
      if (!user) {
        router.push('/auth/login');
      } else {
        loadReport();
      }
    }
  }, [authLoading, user, reportType]);

  const loadReport = async () => {
    try {
      setLoading(true);
      setError('');

      const token = localStorage.getItem('auth_token');
      const response = await fetch(`/api/reports?type=${reportType}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (!response.ok) {
        throw new Error('获取报告失败');
      }

      const result = await response.json();
      if (result.success && result.data) {
        setReport(result.data);
      } else {
        throw new Error('报告数据格式错误');
      }
    } catch (err) {
      console.error('加载报告错误:', err);
      setError('加载报告失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const formatTime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    if (hours > 0) {
      return `${hours}小时${minutes}分钟`;
    }
    return `${minutes}分钟`;
  };

  if (authLoading || loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <Card className="max-w-md">
          <CardContent className="pt-6">
            <p className="text-red-600 text-center">{error}</p>
            <Button onClick={loadReport} className="w-full mt-4">重试</Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!report) {
    return null;
  }

  const { summary, strongTopics, weakTopics, trend, progressTrend, suggestions } = report;

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      <div className="max-w-6xl mx-auto p-4 md:p-6 space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => router.push('/dashboard')}
              className="flex items-center gap-2"
            >
              <ArrowLeft className="w-4 h-4" />
              返回
            </Button>
            <h1 className="text-3xl font-bold text-gray-900">学习报告</h1>
          </div>

          {/* Report Type Selector */}
          <div className="flex gap-2">
            <Button
              variant={reportType === 'weekly' ? 'default' : 'outline'}
              onClick={() => setReportType('weekly')}
            >
              周报
            </Button>
            <Button
              variant={reportType === 'monthly' ? 'default' : 'outline'}
              onClick={() => setReportType('monthly')}
            >
              月报
            </Button>
          </div>
        </div>

        {/* Summary Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">总题数</p>
                    <p className="text-2xl font-bold">{summary.totalQuestions}</p>
                  </div>
                  <BarChart3 className="w-8 h-8 text-blue-500" />
                </div>
              </CardContent>
            </Card>
          </motion.div>

          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}>
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">正确率</p>
                    <p className="text-2xl font-bold text-green-600">{summary.accuracy}%</p>
                  </div>
                  <CheckCircle className="w-8 h-8 text-green-500" />
                </div>
              </CardContent>
            </Card>
          </motion.div>

          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">学习时长</p>
                    <p className="text-2xl font-bold text-purple-600">{formatTime(summary.totalTime)}</p>
                  </div>
                  <Clock className="w-8 h-8 text-purple-500" />
                </div>
              </CardContent>
            </Card>
          </motion.div>

          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}>
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">练习天数</p>
                    <p className="text-2xl font-bold text-orange-600">{summary.practiceDays}天</p>
                  </div>
                  <Calendar className="w-8 h-8 text-orange-500" />
                </div>
              </CardContent>
            </Card>
          </motion.div>
        </div>

        {/* Progress Trend */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Target className="w-5 h-5" />
              学习趋势
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-4 mb-4">
              {progressTrend === 'improving' && (
                <div className="flex items-center gap-2 text-green-600">
                  <TrendingUp className="w-5 h-5" />
                  <span className="font-medium">稳步提升</span>
                </div>
              )}
              {progressTrend === 'declining' && (
                <div className="flex items-center gap-2 text-red-600">
                  <TrendingDown className="w-5 h-5" />
                  <span className="font-medium">需要加油</span>
                </div>
              )}
              {progressTrend === 'stable' && (
                <div className="flex items-center gap-2 text-blue-600">
                  <Award className="w-5 h-5" />
                  <span className="font-medium">保持稳定</span>
                </div>
              )}
            </div>
            
            {/* Simple trend visualization */}
            <div className="space-y-2">
              {trend.map((day: any, index: number) => (
                <div key={index} className="flex items-center gap-2">
                  <span className="text-sm text-gray-600 w-24">{day.stat_date}</span>
                  <div className="flex-1 bg-gray-200 rounded-full h-4 overflow-hidden">
                    <div 
                      className={`h-full rounded-full ${
                        (day.accuracy || 0) >= 80 ? 'bg-green-500' : 
                        (day.accuracy || 0) >= 60 ? 'bg-yellow-500' : 'bg-red-500'
                      }`}
                      style={{ width: `${day.accuracy || 0}%` }}
                    />
                  </div>
                  <span className="text-sm font-medium w-12">{day.accuracy || 0}%</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Strong and Weak Topics */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Strong Topics */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-green-600">
                <Award className="w-5 h-5" />
                优势知识点
              </CardTitle>
            </CardHeader>
            <CardContent>
              {strongTopics.length > 0 ? (
                <div className="space-y-3">
                  {strongTopics.map((topic: any, index: number) => (
                    <div key={index} className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                      <div>
                        <p className="font-medium">{topic.topic_name}</p>
                        <p className="text-sm text-gray-600">{topic.total_count}题</p>
                      </div>
                      <div className="text-right">
                        <p className="text-lg font-bold text-green-600">{topic.accuracy}%</p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500 text-center py-4">暂无数据</p>
              )}
            </CardContent>
          </Card>

          {/* Weak Topics */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-red-600">
                <Target className="w-5 h-5" />
                待提高知识点
              </CardTitle>
            </CardHeader>
            <CardContent>
              {weakTopics.length > 0 ? (
                <div className="space-y-3">
                  {weakTopics.map((topic: any, index: number) => (
                    <div key={index} className="flex items-center justify-between p-3 bg-red-50 rounded-lg">
                      <div>
                        <p className="font-medium">{topic.topic_name}</p>
                        <p className="text-sm text-gray-600">{topic.total_count}题</p>
                      </div>
                      <div className="text-right">
                        <p className="text-lg font-bold text-red-600">{topic.accuracy}%</p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500 text-center py-4">表现优秀！</p>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Suggestions */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              💡 学习建议
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ul className="space-y-2">
              {suggestions.map((suggestion: string, index: number) => (
                <li key={index} className="flex items-start gap-2">
                  <span className="text-indigo-600 mt-1">•</span>
                  <span className="text-gray-700">{suggestion}</span>
                </li>
              ))}
            </ul>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
